import React, { useState, useEffect, forwardRef, useRef } from 'react';

import Search from '@/components/search/Search.jsx';
import message from '@/components/message/Message';
import RoadInfo from '@/pages/takeATaxi/components/RoadInfo.jsx';

import { dragDom, createElastic } from '@/utils/public';
import axios from '@/utils/request';
import { urlMap } from '@/api/baiduMap';

import './takeATaxi.scoped.less';

const SelectPlace = forwardRef((props, ref) => {
  const { routerAnimationIn } = props;
  const [, r] = useState(0);
  const render = () => {
    r(Math.random());
  };
  const refSelectPlace = useRef();
  const refMap = useRef(); // 地图ref
  const refRoadInfo = useRef(); // 路线详情ref
  const timer = useRef(); //定时器
  const page = useRef({
    roadInfoShow: false, // 是否显示路线详情
    roadWrapShow: false, // 是否显示路线详情
  });
  const [placeList, setPlaceList] = useState([]); // 输入出发地点列表
  const [endPlaceList, setEndPlaceList] = useState([]); // 输入目的地列表
  const [city, setCity] = useState({ content: { address_detail: {} } }); // 当前城市
  const [currentMap, setCurrentMap] = useState({}); // 地图实例
  const [pointList, setPointList] = useState([]); // 保存出发点目的点
  const [roadList, setRoadList] = useState([]); // 路线详情
  // const [roadInfoShow, setRoadInfoShow] = useState(false);
  // const [roadWrapShow, setRoadWrapShow] = useState(false);

  // 获取ip地址,初始化地图
  const getAddress = async () => {
    const map = new BMapGL.Map(refMap.current); // 创建地图
    setCurrentMap(map);
    // 获知地图和标点
    const renderPoint = (lng, lat) => {
      const point = new BMapGL.Point(lng, lat);
      setPointList([point]);
      map.centerAndZoom(point, 13);
      map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      map.setHeading(0); //设置地图旋转角度
      // map.setTilt(80); //设置地图的倾斜角度

      // 设置当前点的标点
      const markerPoint = new BMapGL.Point(lng, lat);
      const marker = new BMapGL.Marker(markerPoint); // 创建标注
      map.addOverlay(marker);

      const scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺控件
      map.addControl(scaleCtrl);
      const zoomCtrl = new BMapGL.ZoomControl(); // 添加缩放控件
      map.addControl(zoomCtrl);
    };

    const position = await new Promise((resolve) => {
      navigator.geolocation.getCurrentPosition(
        (res) => {
          resolve(res);
        },
        () => {
          resolve(false);
        },
        { timeout: 500 }
      );
    });
    let x;
    let y;
    // 获取当前城市
    const IPAddress = await axios.get(urlMap.getIPAddress, { params: { coor: 'bd09ll' } });
    console.log('当前城市', IPAddress);
    if (IPAddress.status === 0) {
      // 保存城市信息
      setCity(IPAddress);
    }
    if (position) {
      x = position.coords.latitude;
      y = position.coords.longitude;
    } else {
      message.error('获取位置信息失败');
      // 获取位置信息失败后定位当前城市
      if (IPAddress.status === 0) {
        const { x, y } = IPAddress.content.point;
        const point = new BMapGL.Point(x, y);
        map.centerAndZoom(point, 13);
        map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
        map.setHeading(65); //设置地图旋转角度
        // map.setTilt(70); //设置地图的倾斜角度
      }
      return;
    }
    // const zPoint = await axios.get(urlMap.geoconv, { params: { coords: `${x},${y}`, from: 1, to: 5 } });
    // console.log(zPoint);
    const pointBak = new BMapGL.Point(y, x);
    const convertor = new BMapGL.Convertor();
    const mapPoint = await new Promise((resolve) => {
      convertor.translate([pointBak], 1, 5, (resPoint) => {
        // console.log('resPoint', resPoint);
        if (resPoint && resPoint.points && resPoint.points.length > 0) {
          y = resPoint.points[0].lng;
          x = resPoint.points[0].lat;
        }
        const point = new BMapGL.Point(y, x);
        const geo = new BMapGL.Geocoder();
        geo.getLocation(point, (res) => {
          resolve(res);
        });
      });
    });

    const { lat, lng } = mapPoint.point;
    renderPoint(lng, lat);
  };
  // 获取地点提示
  const searchPlace = async (value, type) => {
    console.log(value);
    const list = await axios.get(urlMap.getAddressTip, {
      params: {
        query: value,
        region: city.content.address_detail.city_code,
        city_limit: true,
        output: 'json',
      },
    });
    console.log('地点', list);
    if (type === 'start') {
      setPlaceList(list.result);
    } else if (type === 'end') {
      setEndPlaceList(list.result);
    }
  };
  // 搜索框选择确定
  const searchSelect = async (item, index) => {
    const { lat, lng } = item.location;
    // currentMap.clearOverlays();
    const markerPoint = new BMapGL.Point(lng, lat);
    // const marker = new BMapGL.Marker(markerPoint); // 创建标注
    // currentMap.addOverlay(marker);
    // currentMap.addOverlay(marker);

    currentMap.clearOverlays(); // 清除覆盖物
    let list = [];
    // 出发地
    if (index === 0) {
      list = [markerPoint, pointList[1]];
    } else {
      // 目的地
      list = [pointList[0], markerPoint];
    }

    // const view = currentMap.getViewport(list);
    // // console.log('list', view);
    // currentMap.centerAndZoom(view.center, view.zoom);

    // console.log(list);
    if (list.length > 1 && list[1]) {
      const roadData = await axios.get(urlMap.drivingRoad, {
        params: {
          origin: `${list[0].lat.toFixed(6)},${list[0].lng.toFixed(6)}`,
          destination: `${list[1].lat.toFixed(6)},${list[1].lng.toFixed(6)}`,
        },
      });
      console.log('路线', roadData);
      if (roadData.status === 0) {
        setRoadList(roadData.result.routes[0].steps);
      }

      const driving = new BMapGL.DrivingRoute(currentMap, {
        renderOptions: { map: currentMap, autoViewport: true },
      });
      driving.search(list[0], list[1]);
      currentMap.setHeading(0); //设置地图旋转角度
      currentMap.setTilt(70); //设置地图的倾斜角度

      page.current.roadInfoShow = true;
      page.current.roadWrapShow = true;
      render();
    }

    setPointList(list);
    setPlaceList([]);
    setEndPlaceList([]);
  };
  // 关闭路线详情弹框
  const closeRoadInfo = () => {
    console.log(page);
    page.current.roadInfoShow = false;
    page.current.roadWrapShow = false;
    render();
  };
  // 点击导航
  const navigation = () => {
    const { lng, lat } = pointList[0];
    const point = new BMapGL.Point(lng, lat);
    currentMap.centerAndZoom(point, 18);
    // currentMap.setTilt(80);
  };

  useEffect(() => {
    props.getRef &&
      props.getRef({ dom: refSelectPlace.current, parentDom: refSelectPlace.current.parentNode }); // 向上传递当前组件dom

    getAddress(); // 初始化地图
    const removeDragDom = dragDom(refRoadInfo.current);

    return () => {
      removeDragDom();
      clearTimeout(timer.current);
    };
  }, []);

  return (
    <div className={`takeATaxi ${routerAnimationIn}`} ref={refSelectPlace}>
      <div className="place" style={{ paddingBottom: 10 }}>
        <span className="fx0">出发地：</span>
        <Search
          className="fx1"
          showList
          field="name"
          fieldKey="uid"
          key="0"
          searchList={placeList}
          valueChange={(value) => searchPlace(value, 'start')}
          selectChange={(value) => searchSelect(value, 0)}
        ></Search>
      </div>
      <div className="place">
        <span className="fx0">目的地：</span>
        <Search
          className="fx1"
          showList
          field="name"
          key="1"
          fieldKey="uid"
          searchList={endPlaceList}
          valueChange={(value) => searchPlace(value, 'end')}
          selectChange={(value) => searchSelect(value, 1)}
        ></Search>
      </div>

      {/* 地图 */}
      <div ref={refMap} className="map"></div>
      {/*  */}

      {/* 路线详情弹框 */}
      <div className={`road-list ${page.current.roadInfoShow ? 'show' : ''}`}>
        <div className={`wrap ${page.current.roadInfoShow ? 'show' : ''}`}></div>
        <div className={`wrap-after ${page.current.roadWrapShow ? 'show' : ''}`}>
          <div className="title">
            <div className="fx">
              <span>路线详情</span>
              <div className="navigation fx-cc" onClick={navigation}>
                <span> 导航</span>
              </div>
            </div>
            <span style={{ fontSize: 18, padding: '4px 12px' }} onClick={closeRoadInfo}>
              x
            </span>
          </div>
          <div className="list">
            <RoadInfo
              list={roadList}
              renderText={(item) => <div dangerouslySetInnerHTML={{ __html: item.instruction }}></div>}
            ></RoadInfo>
          </div>
        </div>
      </div>

      {/* 展开详情图表-图表 */}
      <div
        className={`road-info fx fx-ai-c fx-jc-c ${page.current.roadInfoShow ? 'none' : ''}`}
        ref={refRoadInfo}
        onClick={() => {
          page.current.roadInfoShow = true;
          page.current.roadWrapShow = true;
          render();
        }}
      >
        <span className="iconfont iconshangla icon"></span>
      </div>

      {/*  */}
    </div>
  );
});

export default SelectPlace;
